//
//  HJNewsDailyController.m
//  KaiChat
//
//  Created by lx on 2024/3/11.
//

#import "HJNewsDailyController.h"
#import "HJNewsDailyCell.h"
#import "HJNewsDailyHeaderView.h"
#import "HJNewsDailyController.h"
#import "HJInformationPresent.h"
#import "HJRefreshHeader.h"
#import "HJRefreshFooter.h"
#import "TJEmptyDataHandler.h"
#import "HJShareController.h"
#import "HJFlutterController.h"

@interface HJNewsDailyController ()<HJInformationCellDelegate>

@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, strong) NSMutableArray *statisticsModels;
@property (nonatomic, strong) NSMutableArray *datas;

@property (nonatomic, strong) NSMutableDictionary *mainDict;


@end

@implementation HJNewsDailyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.pageIndex = 1;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJNewsDailyCell.class forCellReuseIdentifier:@"HJNewsDailyCell"];
    [self.tableView registerClass:HJNewsDailyHeaderView.class forHeaderFooterViewReuseIdentifier:@"HJNewsDailyHeaderView"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.bottom.offset(0);
    }];
    
    self.tableView.mj_header = [HJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer = [HJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;

    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *datas = self.datas[section][@"datas"];
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJNewsDailyLayout *layout = self.datas[indexPath.section][@"datas"][indexPath.row];
    HJNewsDailyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJNewsDailyCell" forIndexPath:indexPath];
    cell.layout = layout;
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJNewsDailyLayout *layout = self.datas[indexPath.section][@"datas"][indexPath.row];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    HJNewsDailyLayout *layout = self.datas[indexPath.section][@"datas"][indexPath.row];
    return layout.height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HJNewsDailyHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HJNewsDailyHeaderView"];
    header.titleLabel.text = self.datas[section][@"title"];
    header.backgroundColor = UIColor.whiteColor;
    header.contentView.backgroundColor = UIColor.whiteColor;
    return header;
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(HJNewsDailyCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.tableView.mj_header.isRefreshing) {
        return;
    }
    
    NSLog(@"%s----%@", __func__, indexPath);
 
    HJNewsDailyLayout *layout = cell.layout;
    [self.statisticsModels addObject:layout];
}


- (void)informationCellDidClickFoldButton:(HJNewsDailyCell *)cell foldButton:(UIButton *)foldButton {
    NSLog(@"%s", __func__);
    
    HJNewsDailyLayout *layout = cell.layout;
    layout.isFold = !layout.isFold;
    [layout calculateLayout];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [UIView setAnimationsEnabled:NO];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [UIView setAnimationsEnabled:YES];
}
 
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"%s", __func__);

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"%s", __func__);
    [self statisticsData];
}

- (void)statisticsData {
    NSLog(@"self.tableView.mj_header.state = %ld", self.tableView.mj_header.state);
    if (self.statisticsModels.count) {
        
        NSMutableArray *newsIds = [NSMutableArray array];
        for (HJNewsDailyLayout *layout  in self.statisticsModels) {
            [newsIds addObject:layout.model.informationId];
        }
        [HJInformationPresent statisticsNew_7_24ViewDataWithType:self.type newsIds:newsIds complete:^(NSError * _Nullable error) {
            if (!error) {
//                for (HJNewsDailyLayout *layout  in self.statisticsModels) {
//                    layout.model.views++;
//                }
                [self.statisticsModels removeAllObjects];
//                [self.tableView reloadData];
            }
        }];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}
 
- (NSArray *)getDatas {
    NSMutableArray *Marr = [NSMutableArray array];
    [self.datas enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [Marr addObjectsFromArray:obj[@"datas"]];
    }];
    return Marr;
}

- (void)loadData {
    if (_datas.count == 0) {
        [self showLoading];
        [self loadNewData];
    }
}

- (void)loadNewData {
    
    self.pageIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    [HJInformationPresent loadNewsListWithType:self.type newsTypeId:self.newsTypeId tags:nil pageIndex:self.pageIndex complete:^(NSInteger serverPageSize, NSArray<HJInformationModel *> * _Nullable news, NSArray <HJFollowModel *>* _Nullable recommendUsers, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        self.pageIndex = 2;
        self.emptyDataHandler.canDisplay = YES;
        self.tableView.mj_header.hidden = NO;
        [self.mainDict removeAllObjects];
        [self hiddenLoading];

        if (!error) {
            if (news.count) {
                self.tableView.mj_footer.hidden = NO;
            }
            if (news.count < serverPageSize) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            
            [self handleModels:news];
        }
        [self.tableView reloadData];
    }];
}


- (void)handleModels:(NSArray *)news {
        
    for (int i = 0; i < news.count; i++) {
        HJInformationModel *model = news[i];
        model.index = i;
        HJNewsDailyLayout *layout = [HJNewsDailyLayout layoutWithModel:model];
        
        NSString *key = [[NSDate dateWithTimeIntervalSince1970:layout.model.publishTimestamp] stringWithFormat:@"dd MMM yyyy"];
        NSMutableArray *dictMarr = [self.mainDict valueForKey:key];
         if (!dictMarr) {
             [self.mainDict setValue:[NSMutableArray array] forKey:key];
             dictMarr = [self.mainDict valueForKey:key];
         }
        [dictMarr addObject:layout];
    }

    [self.datas removeAllObjects];
    
    NSArray *sortKeys = [self.mainDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
    
        NSArray *obj1Datas = [self.mainDict valueForKey:obj1];
        HJNewsDailyLayout *layoutl = obj1Datas.firstObject;
        
        NSArray *obj2Datas = [self.mainDict valueForKey:obj2];
        HJNewsDailyLayout *layout2 = obj2Datas.firstObject;
        
        return layoutl.model.publishTimestamp < layout2.model.publishTimestamp;
    }];
    
    [sortKeys enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.datas addObject:@{@"title": obj, @"datas": self.mainDict[obj]}];
    }];
    [self.tableView reloadData];
}


- (void)loadMoreData {
    [HJInformationPresent loadNewsListWithType:self.type newsTypeId:self.newsTypeId tags:nil pageIndex:self.pageIndex complete:^(NSInteger serverPageSize, NSArray<HJInformationModel *> * _Nullable news, NSArray <HJFollowModel *>* _Nullable recommendUsers, NSError * _Nullable error) {
        
        [self.tableView.mj_footer endRefreshing];

        if (error) {
            return;
        }
      
        self.pageIndex++;
        
        if (news.count < serverPageSize) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        if (news.count) {
            [self handleModels:news];
         }
        [self.tableView reloadData];
    }];
}
 

- (NSMutableArray *)statisticsModels {
    if (!_statisticsModels) {
        _statisticsModels = [NSMutableArray array];
    }
    return _statisticsModels;
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableDictionary *)mainDict {
    if (!_mainDict) {
        _mainDict = [NSMutableDictionary dictionary];
    }
    return _mainDict;
}

@end

 
